package com.shenghui.enterprise.base.entity;

import com.shenghui.enterprise.utils.UserUtil;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.Date;

@Component
public class EntityCommon {
    @Resource
    UserUtil userUtil;

    public <T> void createBase(T t) {
        try {
            Class entityClass = (Class) t.getClass();
            try {
                Method setCreateDate = entityClass.getMethod("setCreateDate", Date.class);
                setCreateDate.invoke(t,new Date());
            }  catch (Exception e) {
            }
            try {
                Method setCreateDate = entityClass.getMethod("setCreateDate", LocalDateTime.class);
                setCreateDate.invoke(t,LocalDateTime.now());
            }  catch (Exception e) {
            }
            try {
                Method setCreateUserId = entityClass.getMethod("setCreateUserId", String.class);
                setCreateUserId.invoke(t, userUtil.getUserId() );
            }  catch (Exception e) {
            }
            try {
                Method setCreateUserName = entityClass.getMethod("setCreateUserName", String.class);
                setCreateUserName.invoke(t,userUtil.getLoginUser().getName());
            }  catch (Exception e) {
            }
            try {
                Method setDeleteMark = entityClass.getMethod("setDeleteMark", Integer.class);
                setDeleteMark.invoke(t, 0);
            }  catch (Exception e) {
            }

        }  catch (Exception e) {
            e.printStackTrace();
        }
    }

    public <T> void modifyBase(T t) {
        try {
            Class entityClass = (Class) t.getClass();
            try {
                Method setSignature = entityClass.getMethod("setSignature",String.class);
                setSignature.invoke(t,"");
            }  catch (Exception e) {
            }
            try {
                Method setCreateDate = entityClass.getMethod("setModifyDate", Date.class);
                setCreateDate.invoke(t,new Date());
            }  catch (Exception e) {
            }
            try {
                Method setCreateDate = entityClass.getMethod("setModifyDate", LocalDateTime.class);
                setCreateDate.invoke(t,LocalDateTime.now());
            }  catch (Exception e) {
            }
            try {
                Method setCreateUserId = entityClass.getMethod("setModifyUserId", String.class);
                setCreateUserId.invoke(t, userUtil.getUserId() );
            }  catch (Exception e) {
            }
            try {
                Method setCreateUserName = entityClass.getMethod("setModifyUserName", String.class);
                setCreateUserName.invoke(t,userUtil.getLoginUser().getName());
            }  catch (Exception e) {
            }

        }  catch (Exception e) {
            e.printStackTrace();
        }
    }

}
